package com.alibaba.shopping_seckill_service.redis;

import com.alibaba.shopping_common.pojo.Orders;
import com.alibaba.shopping_common.pojo.SeckillGoods;
import com.alibaba.shopping_common.service.SeckillService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * @ClassName RedisKeyExpirationListener
 * @Description TODO
 * @Author Leo
 * @Date 2024/12/23 09:53
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private SeckillService seckillService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }


    /**
     * 订单过期的监听方法
     *  订单过期后，交易关闭，回补库存
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取失效key，即订单ID
        String expireKey = message.toString();
        // 查询Redis中的订单副本数据
        Orders orders = (Orders) redisTemplate.opsForValue().get(expireKey + "_copy");
        // 获取商品ID
        Long goodId = orders.getCartGoods().get(0).getGoodId();
        // 商品件数
        Integer num = orders.getCartGoods().get(0).getNum();
        // 根据订单上的商品ID实时查询Redis中秒杀商品信息
        SeckillGoods seckillGoods = seckillService.findSeckillGoodsByRedis(goodId);
        // 回补库存
        seckillGoods.setStockCount(seckillGoods.getStockCount()+num);
        redisTemplate.boundHashOps("seckillGoods").put(goodId,seckillGoods);
        // 删除订单副本数据
        redisTemplate.delete(expireKey+"_copy");
    }
}




